<script setup>
import { onMounted, ref, watch } from "vue";
import { pageApi, addApi, showBackApi, updateApi, delByIdsApi } from "@/api/emp";
import { queryAllApi } from "@/api/dept";
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// const imageUrl = ref(null)
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  form.value.image = response.data
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('上传图片必须是JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片不得超过2MB!')
    return false
  }
  return true
}
const ruleForm = ref(null)
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});
const searchEmp = ref({
  name: "",
  gender: "",
  begin: "",
  end: "",
  date: [],
});
const form = ref({
  id: '',
  username: "",
  name: "",
  gender: "",
  phone: "",
  job: "",
  salary: "",
  image: "",
  entryDate: "",
  deptId: "",
  createTime: "",
  updateTime: "",
  exprList: []
});
const titleName = ref("");
const size = ref("default");
const empList = ref([]);
const deptList = ref([]);
const genderList = ref([
  { id: '1', name: '男' },
  { id: '2', name: '女' }
])
const jobList = ref([
  { id: '1', name: '班主任' },
  { id: '2', name: '讲师' },
  { id: '3', name: '咨询师' },
  { id: '4', name: '其它' }
])
// const exprList = ref([])
const Reset = () => {
  searchEmp.value = {
    name: "",
    gender: "",
    date: [],
  };
  searchByPage();
};
watch(
  () => searchEmp.value.date,
  (newDate, oldDate) => {
    if (newDate.length == 2) {
      searchEmp.value.begin = newDate[0];
      searchEmp.value.end = newDate[1];
    } else {
      searchEmp.value.begin = "";
      searchEmp.value.end = "";
    }
  }
);
watch(form, (newValue, oldValue) => {
  if (form.value.exprList) {
    form.value.exprList.forEach(expr => {
      expr.begin = expr.exprDate[0]
      expr.end = expr.exprDate[1]
    })
  }
}, { deep: true })
const dialogVisible = ref(false);
const background = ref(true);
const disabled = ref(false);

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const handleSizeChange = (val) => {
  pageSize.value = val;
  searchByPage();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  searchByPage();
};
const close = () => {
  dialogVisible.value = false
  ruleForm.value.resetFields()
  // ruleForm.resetField()
  form.value = {
    id: '',
    username: "",
    name: "",
    gender: "",
    phone: "",
    job: "",
    salary: "",
    image: "",
    entryDate: "",
    deptId: "",
    createTime: "",
    updateTime: "",
    exprList: []
  }
}
const showBack = async (id) => {
  // console.log('sea')
  dialogVisible.value = true
  titleName.value = '修改信息'
  const res = await showBackApi(id)
  form.value = {
    ...res.data,
    exprList: res.data.exprList || []  // 如果后端没返回 exprList，就用空数组兜底
  };
  let exprList = form.value.exprList
  if (exprList && exprList.length > 0) {
    exprList.forEach(expr => {
      expr.exprDate = [expr.begin, expr.end]
    })
  }
}
const ids = ref([])
const handleSelectionChange = (val) => {
  ids.value = val.map(item => item.id)
}

const delById = (id) => {
  ids.value = id
  delByIds()
}
const delByIds = async () => {
  let res = await delByIdsApi(ids.value)
  if (res.code) {
    ElMessage.success('操作成功!')
    ids.value = []
    searchByPage()
  } else {
    ElMessage.error('操作失败!')
  }
}
const addEmpList = async () => {
  if (!ruleForm) return
  let res = null
  await ruleForm.value.validate(async (valid, fields) => {
    if (valid) {
      if (form.value.id) {
        res = await updateApi(form.value)
      } else {
        res = await addApi(form.value)
      }
      if (res.code) {
        ElMessage.success('操作成功!')
        dialogVisible.value = false
        close()
        searchByPage()
      } else {
        ElMessage.error('操作失败!')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const searchByPage = async () => {
  const res = await pageApi(
    searchEmp.value.name,
    searchEmp.value.gender,
    searchEmp.value.begin,
    searchEmp.value.end,
    currentPage.value,
    pageSize.value
  );
  empList.value = res.data.rows;
  total.value = res.data.total;
};
const listDept = async () => {
  const res = await queryAllApi();
  deptList.value = res.data;
};
const addExprList = () => {
  form.value.exprList.push({ exprDate: [], begin: '', end: '', company: '', job: '' })
}
const delExprList = (index) => {
  form.value.exprList.splice(index, 1)
}
onMounted(() => {
  searchByPage();
  listDept();
});
</script>

<template>
  <el-button type="primary" @click="dialogVisible = true"> 新增 </el-button>
  <el-button type="danger" @click="delByIds()"> 批量删除 </el-button>
  <br />
  <br />
  <el-dialog v-model="dialogVisible" :title="titleName" width="800">
    <el-form :model="form" label-width="auto" style="max-width: 700px" ref="ruleForm" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择">
              <el-option v-for="gender in genderList" :key="gender.id" :label="gender.name" :value="gender.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="job">
            <el-select v-model="form.job" placeholder="请选择">
              <el-option v-for="job in jobList" :key="job.id" :label="job.name" :value="job.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="日期">
            <el-col :span="11">
              <el-date-picker v-model="form.entryDate" type="date" placeholder="选择日期" style="width: 280px" />
              <!-- <el-date-picker v-model="form.entryDate" type="daterange" range-separator="到" start-placeholder="开始日期"
        end-placeholder="结束日期" :size="size" style="width: 250px;"/> -->
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="form.salary" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门">
            <el-select v-model="form.deptId" placeholder="请选择">
              <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="form.image" :src="form.image" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
    <br />
    <br />
    <span>工作经历</span>
    <el-row v-for="(expr, index) in form.exprList">
      <el-col>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="时间">
              <el-date-picker v-model="expr.exprDate" type="daterange" range-separator="到" start-placeholder="开始日期"
                end-placeholder="结束日期" style="width: 50px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公司">
              <el-input v-model="expr.company" placeholder="请输入公司名字" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="职位">
              <el-input v-model="expr.job" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-button type="danger" @click="delExprList(index)">删除</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-button type="success" @click="addExprList()" style="margin-right: auto;">添加</el-button>
    </el-row>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="addEmpList()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-form :inline="true" :model="searchEmp">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入姓名" />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="请选择性别">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <span class="demonstration">时间 </span>
      <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="到" start-placeholder="开始日期"
        end-placeholder="结束日期" :size="size" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchByPage">查询</el-button>
      <el-button type="primary" @click="Reset">清空</el-button>
    </el-form-item>
  </el-form>


  <!-- 分页过后的表格数据 -->
  <el-table :data="empList" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column fixed prop="id" label="ID" width="150" />
    <el-table-column prop="username" label="用户名" width="120" />
    <el-table-column prop="name" label="姓名" width="120" />
    <el-table-column prop="image" label="头像" width="120">
      <template #default="{ row }">
        <img :src="row.image" width="50px" />
      </template>
    </el-table-column>
    <el-table-column prop="gender" label="性别" width="60">
      <template #default="{ row }">
        {{ row.gender == 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column prop="job" label="职位" width="60" />
    <el-table-column prop="salary" label="薪水" width="120" />
    <el-table-column prop="entryDate" label="入职如期" width="120" />
    <el-table-column prop="deptId" label="部门id" width="120" />
    <el-table-column prop="deptName" label="部门名字" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="120" />
    <el-table-column prop="updateTime" label="更新时间" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="{ row }">
        <el-button link type="primary" size="small" @click="showBack(row.id)">
          编辑
        </el-button>
        <el-button link type="danger" size="small" @click="delById(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br />
  <div class="demo-pagination-block">
    <!-- <div class="demonstration">All combined</div> -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>
<!-- 总条数, sizes, 上一页, pager, 下一页, 跳转至 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
